"use strict";

import axios from "axios";
import Qs from "qs";
import { message } from "ant-design-vue";
import { Loading } from "element-ui";

// console.log(process.env);

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || "";
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

let loading;
let msgTimeout = 3000;
let config = {
  baseURL: process.env.VUE_APP_axiosBaseUrl,
  timeout: 60 * 1000, // Timeout
  withCredentials: true // Check cross-site Access-Control
};
let extra =
  process.env.NODE_ENV == "development"
    ? { com_id: "5", user: "300000002" }
    : {};
let _axios = axios.create(config);
_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    let param = config.data || config.params;
    if (param && "noloading" in param) {
      delete param.noloading;
      param = null;
    } else {
      loading = Loading.service({
        fullscreen: true,
        body: true,
        lock: true,
        background: "rgba(255,255,255,0)",
        text: "努力加载中..."
      });
    }
    if (config.method === "post") {
      config.data = { ...extra, ...config.data };
      config.data = Qs.stringify(config.data);
    } else {
      config.params = { ...extra, ...config.params };
    }
    return config;
  },
  function(error) {
    // Do something with request error
    message.error(error, msgTimeout);
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    loading && loading.close();
    // Do something with response data
    return response.data;
  },
  function(error) {
    // Do something with response error
    message.error(error || "服务器请求出错!", msgTimeout);
    return Promise.reject(error);
  }
);
export default {
  http: _axios,
  install(Vue) {
    Vue.axios = _axios;
    window.axios = _axios;
    Object.defineProperties(Vue.prototype, {
      axios: {
        get() {
          return _axios;
        }
      },
      $axios: {
        get() {
          return _axios;
        }
      }
    });
  }
};
